// pages/cart/cart.js
import {
  unix
} from 'dayjs';
import {
  cartPage,
  cartDelete
} from '../../common/api/cart'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navBarHeight: getApp().globalData.navBarHeight,
    statusBarHeight: getApp().globalData.statusBarHeight,
    bgHeight: 220,
    goodsData: [1],
    list: [],
    page: 1,
    isMore: false,
    totalPrices: 0,
    isAll: false,
    width: 0, // 胶囊宽度
    type: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const res = wx.getMenuButtonBoundingClientRect();
    this.setData({
      bgHeight: this.data.statusBarHeight > 20 ? (this.data.statusBarHeight - 20) * 2 + 220 : 220,
      width: res.width
    })
  },

  onReachBottom() {
    if (this.data.isMore) {
      console.log('没有更多了')
      return
    }
    this.data.page += 1;
    this.getData();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.data.list = [];
    this.setData({
      list: []
    })
    this.data.page = 1;
    this.data.isMore = false;
    this.getData();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },



  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(e){
    let user = wx.getStorageSync('userInfo');
    console.log(e);
    return {
      title: "杆赢天下，求胜未来。一元乐享好球杆，千万球友的选择",
      imageUrl: "../../images/shareImg.jpg",
       path: "/pages/index/index?id=" + user.id
    }
  },
  // 减去
  minus(e) {
    let num = e.currentTarget.dataset.item.cartNumber;
    if (num == 1) {
      return
    }
    num -= 1;
    this.setData({
      ["list[" + e.currentTarget.dataset.index + "].cartNumber"]: num
    });
    this.calculate();
  },
  add(e) {
    let num = e.currentTarget.dataset.item.cartNumber;
    num += 1;
    this.setData({
      ["list[" + e.currentTarget.dataset.index + "].cartNumber"]: num
    });
    this.calculate();
  },
  pitchOn(e) {
    let val = !e.currentTarget.dataset.item.isTrue;
    this.setData({
      ["list[" + e.currentTarget.dataset.index + "].isTrue"]: val
    })
    this.calculate();
  },
  // 全选
  pitchOnAll() {
    this.data.list.forEach(e => {
      e.isTrue = true;
    });
    this.setData({
      list: this.data.list
    });
    this.calculate();
  },
  calculate() {
    let num = 0; // 价格
    let num2 = 0;
    let isAll = false;
    console.log(this.data.list)
    this.data.list.forEach(e => {
      if (e.isTrue) {
        num += e.cartNumber * e.retailPrice;
        num2 += 1;
        // console.log(num, e.cartNumber,e.retailPrice,e)
      };
      if (this.data.list.length == num2) {
        isAll = true;
      }
    });

    this.setData({
      totalPrices: num,
      isAll: isAll
    })
  },
  // 获取分页
  async getData() {
    let user = wx.getStorageSync('userInfo');
    let res = await cartPage({
      goodsName: '',
      userId: user.id,
      page: this.data.page,
      size: 10
    });
    if ((res.list || []).length < 10) {
      this.data.isMore = true;
    }
    let a = [...this.data.list, ...(res.list || [])];

    this.setData({
      list: a,
      isAll: false,
      totalPrices: 0,
      type: true
    })
  },
  // 立即换取
  immediateExchange() {
    let arr = (this.data.list || []).filter(e => e.isTrue);
    if (arr.length) {
      let arr2 = [];
      arr.forEach(e => {

        arr2.push({
          num: e.cartNumber,
          id: e.goodsId,
          cartId: e.id
        })
      });

      let idObj = JSON.stringify(arr2);
      wx.navigateTo({
        url: "/pages/allShop/submitorder/submitorder?id=" + idObj,
      });
    } else {
      if ((this.data.list || []).length) {
        wx.showToast({
          title: '请选择换取的商品',
          icon: 'none'
        })
      } else {
        wx.showToast({
          title: '请您先在购物车里面添加换取商品',
          icon: 'none'
        });

      }

    };
  },
  async removeCart() {
    let arr = (this.data.list || []).filter(e => e.isTrue);
    let url = 'cart/delete'
    if (arr.length) {
      let arr2 = [];
      arr.forEach((e, index) => {
        console.log(e, index)
        // arr2.push({
        //   // num: e.cartNumber,
        //   // id: e.goodsId,
        //   cartId: e.id
        // })
        if (index == 0) {
          url = url + '?ids=' + e.id
        } else {
          url = url + '&ids=' + e.id
        }

      });

      let res = await cartDelete(url, {});
      // 充值
      this.setData({
        list: []
      });
      wx.showToast({
        title: '移除成功'
      })
      this.data.page = 1;
      this.data.isMore = false;
      this.getData();

    } else {
      if ((this.data.list || []).length) {
        wx.showToast({
          title: '请选择换取的商品',
          icon: 'none'
        })
      } else {
        wx.showToast({
          title: '请您先在购物车里面添加换取商品',
          icon: 'none'
        });

      }

    };
  },
  //  切换类型
  cutType() {
    this.setData({
      type: !this.data.type
    })
  },
  go(e) {
    wx.navigateTo({
      url: '../allShop/shopDetail/shopDetail?id=' + e.currentTarget.dataset.item.goodsId + "&notCart=true",
      // url: '../shopDetail/shopDetail?id='+ e.currentTarget.dataset.item.id,
    });
  },
  // 数量控制器
  handleChange(e) {
    this.setData({
      ["list[" + e.currentTarget.dataset.index + "].cartNumber"]: e.detail.value
    });
    this.calculate();
  },
})